package com.dmbjz.consumer;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.dmbjz.config.RabbitConfig;
import com.dmbjz.dao.DeliverymanDao;
import com.dmbjz.entity.dto.OrderMessageDTO;
import com.dmbjz.entity.po.DeliverymanPO;
import com.dmbjz.enummeration.DeliverymanStatus;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static com.dmbjz.enummeration.OrderStatus.DELIVERTMAN_CONFIREED;

/* 骑手监听 */
@Component
@Slf4j
public class DeliveryConsumer {

    @Autowired
    private DeliverymanDao deliverymanDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = RabbitConfig.DELIVERYMAN_QUEUE,containerFactory = "rabbitListenerContainerFactory")
    public void orderMessage(Message message, Channel channel) throws IOException {

        OrderMessageDTO messageDTO = JSON.parseObject(new String(message.getBody()), OrderMessageDTO.class);

        List<DeliverymanPO> deliverymanList = deliverymanDao.selectAvaliableDeliveryman(DeliverymanStatus.AVALIABLE);    //获取目前所有空闲状态的骑手信息
        if(CollectionUtil.isNotEmpty(deliverymanList)){

            messageDTO.setDeliverymanId(deliverymanList.get(0).getId());
            messageDTO.setOrderStatus(DELIVERTMAN_CONFIREED);   // 更新订单状态为骑手已送达
            log.info("订单已分配骑手,当前消息:{}", messageDTO);

            /* 发送消息 */
            MessageProperties properties = new MessageProperties();
            properties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
            properties.setContentEncoding("utf-8");
            String jsonMsg = JSON.toJSONString(messageDTO);
            Message sendMsg = new Message(jsonMsg.getBytes(StandardCharsets.UTF_8),properties);

            CorrelationData correlationData = new CorrelationData();
            ReturnedMessage returnedMessage = new ReturnedMessage(sendMsg,300,"骑手已送达订单，发送给消息给餐厅交换机",
                    RabbitConfig.DELIVERYMAN_EXCHANGE,
                    "key.order");
            correlationData.setReturned(returnedMessage);
            correlationData.setId(messageDTO.getOrderID());     //设置订单ID
            rabbitTemplate.convertAndSend( RabbitConfig.DELIVERYMAN_EXCHANGE,"key.order",sendMsg,correlationData);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);        //订单确认
        }else{

            log.info("订单暂无可分配的骑手,情耐心等待,当前消息状态:{}", messageDTO);

        }


    }


}
